package com.heima.behavior.service.impl;

import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.common.exception.CustException;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.common.enums.AppHttpCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class ApBehaviorEntryServiceImpl implements ApBehaviorEntryService {
    @Autowired
    MongoTemplate mongoTemplate;
    @Override
    public ApBehaviorEntry findByUserIdOrEquipmentId(Integer userId, Integer equipmentId) {
        if (userId!=null){
            Query query = Query.query(Criteria.where("refId").is(userId).and("type").is(1));
            List<ApBehaviorEntry> apComments = mongoTemplate.find(query, ApBehaviorEntry.class);
            log.info("查询行为实体对象"+apComments);
            if (apComments.size()==0){
                ApBehaviorEntry apComment = ApBehaviorEntry.builder()
                        .refId(userId)
                        .type((short)1)
                        .createdTime(new Date())
                        .build();
                mongoTemplate.insert(apComment);
                return apComment;
            }
            return apComments.get(0);
        }else if (equipmentId!=null){
            Query query = Query.query(Criteria.where("refId").is(equipmentId).and("type").is(0));
            ApBehaviorEntry apComments = mongoTemplate.findOne(query, ApBehaviorEntry.class);
            log.info("查询行为实体对象"+apComments);
            if (apComments==null){
                ApBehaviorEntry apComment = ApBehaviorEntry.builder()
                        .refId(equipmentId)
                        .type((short)0)
                        .createdTime(new Date())
                        .build();
                mongoTemplate.insert(apComment);
                return apComment;
            }
            return apComments;
        }
        return null;
    }
}
